﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BusinessObjects;
using System.ComponentModel.DataAnnotations.Schema;

namespace DataAccess.EntityModels
{
    public class DatabaseContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<Permission> Permissions { get; set; }

        public DatabaseContext() : base ("SampleSecurityApplication")
        {

        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<RoleUser>()
                .HasKey(ru => new { ru.RoleId, ru.UserId })
                .ToTable("RolesUsers");

            modelBuilder.Entity<User>()
                .HasMany(u => u.RolesUsers)
                .WithRequired()
                .HasForeignKey(ru => ru.UserId);

            modelBuilder.Entity<Role>()
                .HasMany(r => r.RolesUsers)
                .WithRequired()
                .HasForeignKey(ru => ru.RoleId);

            
            modelBuilder.Entity<RolePermission>()
                .HasKey(rp => new { rp.RoleId, rp.PermissionId })
                .ToTable("RolesPermissions");

            modelBuilder.Entity<Permission>()
                .HasMany(p => p.RolesPermissions)
                .WithRequired()
                .HasForeignKey(rp => rp.PermissionId);

            modelBuilder.Entity<Role>()
                .HasMany(r => r.RolesPermissions)
                .WithRequired()
                .HasForeignKey(rp => rp.RoleId);

            modelBuilder.Entity<User>()
                .HasKey(user => user.Id)
                .Property(user => user.Id)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            modelBuilder.Entity<User>()
                .Property(user => user.Name);

            modelBuilder.Entity<Role>()
                .HasKey(role => role.Id)
                .Property(role => role.Id)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            modelBuilder.Entity<Role>()
                .Property(role => role.Name);

            modelBuilder.Entity<Permission>()
                .HasKey(permission => permission.Id)
                .Property(permission => permission.Id)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            modelBuilder.Entity<Permission>()
                .Property(permission => permission.Name);

            base.OnModelCreating(modelBuilder);
        }
    }
}
